package ls.jpa.chapterA.repository.impl;

import com.mysema.query.jpa.impl.JPAQuery;
import com.mysema.query.types.expr.BooleanExpression;
import ls.jpa.chapterA.domain.Customer;
import ls.jpa.chapterA.domain.Customer_;
import ls.jpa.chapterA.domain.QCustomer;
import org.apache.log4j.Logger;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.Calendar;
import java.util.List;

import static ls.jpa.chapterA.expressions.CustomerExpressions.isLongTermCustomer;

/**
 * @author Barudisshu
 */
public class CustomerRepositoryImpl {

    private static final Logger logger = Logger.getLogger(CustomerRepositoryImpl.class);

    @PersistenceContext
    private EntityManager entityManager;

    public List<Customer> findByFirstName(String firstName){
        CriteriaBuilder builder = entityManager.getCriteriaBuilder();
        CriteriaQuery<Customer> query = builder.createQuery(Customer.class);
        Root<Customer> root = query.from(Customer.class);
        query.where(builder.equal(root.get("firstName"),firstName));
        return entityManager.createQuery(query.select(root)).getResultList();
    }

    public List<Customer> findByLastName(String lastName){
        CriteriaBuilder builder = entityManager.getCriteriaBuilder();
        CriteriaQuery<Customer> query = builder.createQuery(Customer.class);
        Root<Customer> root = query.from(Customer.class);
        Predicate lnp = builder.equal(root.get(Customer_.lastName),lastName);
        query.where(builder.and(lnp));
        return entityManager.createQuery(query.select(root)).getResultList();
    }

    // Query DSL
    public List<Customer> findByVersion(Long version){
        Calendar calendar = Calendar.getInstance();
        QCustomer customer = QCustomer.customer;
        BooleanExpression hasBirthday = customer.birthday.eq(calendar.getTime());
        calendar.add(Calendar.YEAR,-2);
        return new JPAQuery(entityManager).from(customer).where(hasBirthday.and(isLongTermCustomer())).list(customer);
    }

}
